package com.cq.cqmall.product.exception;

import com.cq.common.exception.BusinessCode;
import com.cq.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * cq商场异常控制器建议
 *
 * @author 程崎
 * @since 2022/09/20
 */
@RestControllerAdvice(basePackages = "com.cq.cqmall.product.controller")
@Slf4j
public class CqMallExceptionControllerAdvice {

    /**
     * 处理校验异常
     *
     * @param e e
     * @return {@link R}
     */
    @ExceptionHandler(BindException.class)
    public R handleValidException(BindException e) {
        log.info("exception info is: {}, the type is: {}", e.getMessage(), e.getClass());
        Map<String, String> map = new HashMap<>(4);
        e.getFieldErrors().forEach(item -> {
            String message = item.getDefaultMessage();
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(BusinessCode.VALID_EXCEPTION.getCode(), BusinessCode.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    /**
     * 处理其他异常
     *
     * @return {@link R}
     */
    @ExceptionHandler(Throwable.class)
    public R handleOtherException(Throwable throwable) {
        return R.error(BusinessCode.UNKNOWN_EXCEPTION.getCode(), BusinessCode.UNKNOWN_EXCEPTION.getMsg());
    }

}
